import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { MyModalHelper } from '@core/my-modal.helper';
import { CacheService } from '@core/routes-services/cache.service';
import { CompanyService } from '@core/routes-services/company.service';
import { myValidNull } from '@core/util/string-utils';
import { MarketFansService } from '@core/routes-services/market-fans.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { debounceTime, switchMap } from 'rxjs/operators';

@Component({
  selector: 'step1points1',
  templateUrl: './step1points1.component.html',
  styles: [`
    h2 {
      border-bottom: 1px solid #1890ff;
      color: #1890ff;
      padding-top: 20px;
    }
  `],
})
export class Step1points1Component implements OnInit {
  entity: any = {};
  profitSettingArr: any [] = [];

  validateForm: FormGroup;
  isLoading: boolean = false;
  componentDirty: boolean = false;

  loadingOption: boolean = false;

  searchChange$ = new BehaviorSubject('');
  fansList: any [] = [];
  profitCusList: any [] = [];


  keyword: any;

  constructor(private router: Router,
              private modalHelper: MyModalHelper,
              public companyService: CompanyService,
              private marketFansService: MarketFansService,
              private message: NzMessageService,
              private cacheService: CacheService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    this.entity = this.companyService.entity;
    let profitSetting = this.companyService.profitSetting;
    this.profitCusList = this.companyService.profitCusList;
    if (!myValidNull(profitSetting)) {
      this.profitSettingArr = JSON.parse(profitSetting);
    }
    this.initValidateForm();
    const searchFanOptions = (name: string) => this.marketFansService.searchOptions(name).then((res) => {
      if (res.status.toString().startsWith('20')) {
        return res.data.content;
      } else {
        this.message.warning(res.message);
        return [];
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      return [];
    });
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(searchFanOptions));
    optionList$.subscribe(data => {
      console.log(data)
      this.fansList = data;
      this.fansList = this.fansList.concat(this.profitCusList);
      this.fansList = this.unique(this.fansList);
      this.loadingOption = false;
    });

  }

  unique(arr) {
    const res = new Map();
    return arr.filter((a) => !res.has(a.id) && res.set(a.id, 1))
  }
  onSearch(value: string): void {
    this.loadingOption = true;
    this.searchChange$.next(value);
  }

  initValidateForm() {
    this.validateForm = this.fb.group({});
    for (const profitSetting of this.profitSettingArr) {
      this.validateForm.addControl('key_' + profitSetting.key, new FormControl(profitSetting.cusId, Validators.required));
      this.validateForm.addControl('value_' + profitSetting.key, new FormControl(profitSetting.profit, Validators.required));
    }
  }


  add() {
    this.componentDirty = true;
    let key = Math.floor(Math.random()*10000);
    this.profitSettingArr.push({ 'key': key, 'cusId': '', 'profit': '' });
    this.validateForm.addControl('key_' + key, new FormControl(null, Validators.required));
    this.validateForm.addControl('value_' + key, new FormControl(null, Validators.required));
  }
  remove(index, key) {
    this.componentDirty = true;
    this.profitSettingArr.splice(index, 1);
    this.validateForm.removeControl('key_' + key);
    this.validateForm.removeControl('value_' + key);
  }

  submitForm() {
    let $this = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      //收益排重 同一个人不能重复添加
      let profitCusIdArr:any [] = [];
      for (const profitSetting of this.profitSettingArr) {
        profitSetting.cusId = this.validateForm.value["key_"+profitSetting.key];
        profitSetting.profit = this.validateForm.value["value_"+profitSetting.key];
        let index = profitCusIdArr.findIndex((r)=>r == profitSetting.cusId);
        if(index >= 0){
          this.message.warning("请不要重复添加相同的受益人")
          return;
        }
        profitCusIdArr.push(profitSetting.cusId);
      }
      let profitSettingStr = JSON.stringify(this.profitSettingArr);

      if (!this.entity.id || this.entity.id == 0) {
        //新增到最后一步再同一保存
        this.companyService.profitSetting = profitSettingStr;
        this.companyService.entity.profitSetting = profitSettingStr;
        this.companyService.entity.profitCusIds = profitCusIdArr.join(",");
        ++this.companyService.step;
      } else {
        //修改
        if (this.validateForm.dirty || this.componentDirty) {
          this.isLoading = true;
          this.companyService.updateEntity(this.entity.id, {profitCusIds: profitCusIdArr.join(","),profitSetting:profitSettingStr}).then((res) => {
            if (res.status.toString().startsWith('20')) {
              this.message.success('保存成功');
              this.entity = res.data;
              this.companyService.entity = res.data;
              this.companyService.profitSetting = profitSettingStr;
              ++this.companyService.step;
            } else {
              this.message.warning(res.message);
            }
            this.isLoading = false;
          }, error => {
            this.message.error(error.message ? error.message : error.error);
            this.isLoading = false;
          });
        } else {
          ++this.companyService.step;
        }
      }
    }
  }

  goBack() {
    this.companyService.reset();
    this.router.navigate(['/company/list']);
  }

}
